package dnl.confij.ini;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
import java.util.Map.Entry;

import org.ini4j.Ini;
import org.ini4j.Profile.Section;

import dnl.confij.BaseConfigurationSource;
import dnl.confij.ConfigException;
import dnl.confij.ConfigParam;
import dnl.confij.ConfigSection;
import dnl.confij.Configuration;

/**
 * Implements an ini configuration source.
 * 
 * @author <a href="mailto:daniel.or@gmail.com">Daniel Or</a>
 * 
 */
public class IniConfigurationSource extends BaseConfigurationSource {


	private Ini ini;

	/**
	 * 
	 * Constructs a new <code>IniConfigurationSource</code> using an ini
	 * <code>File</code>.
	 * 
	 * @param iniFile
	 */
	public IniConfigurationSource(File iniFile) {
		super(iniFile);
	}

	@Override
	protected void loadConfigurationImpl(Configuration config)
			throws ConfigException {
		try {
			ini = new Ini(new FileReader(getConfigFile()));
		} catch (Exception e) {
			throw new ConfigException(e);
		}
		Collection<Section> iniSections = ini.values();
		for (Section section : iniSections) {
			ConfigSection cs = new ConfigSection(section.getName());
			config.addSection(cs);
			Set<Entry<String, String>> sectionEntries = section.entrySet();
			for (Entry<String, String> entry : sectionEntries) {
				cs.setParamValue(entry.getKey(), entry.getValue());
			}
		}

	}

	@Override
	protected void saveConfigurationImpl(Configuration config)
			throws ConfigException {
		ini.clear();

		Collection<ConfigSection> sections = config.getSections();
		for (ConfigSection section : sections) {
			Section sect = ini.add(section.getName());
			Collection<ConfigParam> configParameters = section.getConfigParameters();
			for (ConfigParam configParam : configParameters) {
				sect.put(configParam.getName(), configParam.getValue());
			}
		}

		try {
			ini.store(new FileWriter(getConfigFile()));
		} catch (IOException e) {
			throw new ConfigException(e);
		}

	}

}
